package com.sisyphus.cloud.eureka;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * 项目名称：spring-cloud-learning
 * 类名称：MainController
 * 类描述：MainController
 * 创建时间：2020/4/9
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
@RestController
public class MainController {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/index")
    public String index() {
        return "hello world";
    }

    @GetMapping("/index2")
    public String index2() {
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://USER-SERVICE/index", String.class);

        return forEntity.getBody();
    }


    @GetMapping("/services")
    public List<String> services() {
        List<String> services = discoveryClient.getServices();
        return services;
    }

    @GetMapping("/description")
    public String description() {
        return discoveryClient.description();
    }

    @GetMapping("/order")
    public int order() {
        return discoveryClient.getOrder();
    }

    @GetMapping(value = "/instances/{serviceId}/meta-data")
    public Map<String, String> instancesMetaData(@PathVariable String serviceId) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        return instances.get(0).getMetadata();
    }

    @GetMapping(value = "/instances/eureka-server/meta-data/{key}")
    public String instances(@PathVariable String serviceId, @PathVariable String key) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        return instances.get(0).getMetadata().get("key");
    }

}
